const fp = require('lodash/fp')
const cars = [
    {name: 'Ferrari FF', horsepower: 660, dollar_value: 700000, in_stock: true},
    {name: 'Spyker C12 Zagato', horsepower: 650, dollar_value: 648000, in_stock: false},
    {name: 'Jaguar XKR-S', horsepower: 550, dollar_value: 132000, in_stock: false},
    {name: 'Audi R8', horsepower: 525, dollar_value: 114200, in_stock: false},
    {name: 'Aston Martin One-77', horsepower: 750, dollar_value: 1850000, in_stock: true},
    {name: 'Pagani Huayra', horsepower: 700, dollar_value: 1300000, in_stock: false},
]

// let isLastInStock = function (cars) {
//     let last_car = fp.last(cars)
//     return fp.prop('name', last_car)
// }
// console.log(isLastInStock(cars))

// 练习一
// let prop_in_stock = fp.prop('in_stock')
// let isLastInStock = fp.flowRight(prop_in_stock, fp.last)

let isLastInStock = fp.flowRight(fp.prop('in_stock'), fp.last)
// console.log('练习一 in_stock:')
console.log(isLastInStock(cars))

// 练习二
// let prop_name = fp.prop('name')
// let firstItemName = fp.flowRight(prop_name, fp.first)

let firstItemName = fp.flowRight(fp.prop('name'), fp.first)
// console.log('\n练习二 name:')
console.log(firstItemName(cars))

// let isLastInStock = fp.flowRight(fp.prop(), fp.last(cars))

// 练习三
// 使用帮助函数 _average 重构 averageDollarValue，使用函数组合的方式实现
let _average = function (xs) {
    return fp.reduce(fp.add, 0, xs) / xs.length
}

// let averageDollarValue = function (cars) {
//     let dollar_values = fp.map(function (car) {
//         return car.dollar_value
//     }, cars)
//     return _average(dollar_values)
// }

let averageDollarValue = fp.flowRight(_average, fp.map(car => car.dollar_value))
console.log(averageDollarValue(cars))

// 练习四 没读懂题目
// 使用flowRight写一个sanitizeNames()函数，返回一个下划线连接的小写字符串，把数组中的name转换为这种形式：例如：sanitizeNames(["Hello World"]) => ["hello_world"]
/*
{
    name: 'Pagani Huayra',
    horsepower: 700,
    dollar_value: 1300000,
    in_stock: false
}
=>
{
    name: 'pagani_huayra',
    horsepower: 700,
    dollar_value: 1300000,
    in_stock: false
}

['Pagani Huayra', 'Pagani Huayra']
=>
['pagani_huayra', 'pagani_huayra']

=>
str str -> str_str
*/

let _underscore = fp.replace(/\W+/g, '_')

let sanitizeName = fp.flowRight(_underscore, fp.toLower)

// let handleName = v => {
//     v['name'] = sanitizeName(v['name'])
//     return v
// }



let handleName = v => fp.assign(v, {name: sanitizeName(v.name)})

let sanitizeNames = fp.map(handleName)
console.log(sanitizeNames(cars))




// console.log(sanitizeNames(cars))
// for (let v of cars) {
//     v.name = _underscore(fp.toLower(v.name))
// }
// console.log(cars)

// 可变形为
// fp.map(function (v) {
//     v.name = _underscore(fp.toLower(v.name))
// })

